package com.example.controller;

import com.example.common.Result;
import com.example.entity.Message;
import com.example.service.MessageService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

// 标记这是一个RESTful控制器
@RestController

// 设置基础URL路径
@RequestMapping("/messages")
public class MessageController {

    // 自动注入MessageService
    @Resource
    private MessageService messageService;

    /**
     * 创建新消息
     */
    @PostMapping("/add")
    public Result createMessage(@RequestBody Message message) {
        messageService.createMessage(message);
        return Result.success("消息发送成功");
    }

    /**
     * 更新消息
     */
    @PutMapping("/update/{mid}")
    public Result updateMessage(@PathVariable Integer mid, @RequestBody Message message) {
        message.setMid(mid);
        messageService.updateMessage(message);
        return Result.success("消息更新成功");
    }

    /**
     * 删除消息
     */
    @DeleteMapping("/delete/{mid}")
    public Result deleteMessage(@PathVariable Integer mid) {
        messageService.deleteMessage(mid);
        return Result.success("消息删除成功");
    }

    /**
     * 根据ID获取消息(消息)
     */
    @GetMapping("/get/{mid}")
    public Result getMessageById(@PathVariable Integer mid) {
        Message message = messageService.getMessageById(mid);
        return Result.success(message);
    }

    /**
     * 获取所有消息
     */
    @GetMapping("/list")
    public Result getAllMessages() {
        List<Message> messages = messageService.getAllMessages();
        return Result.success(messages);
    }

    /**
     * 分页查询消息
     */
    @GetMapping("/selectPage")
    public Result selectPage(Message message,
                             @RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize) {
        PageInfo<Message> page = messageService.selectPage(message, pageNum, pageSize);
        return Result.success(page);
    }

    /**
     * 根据用户ID查询收到的消息
     */
    @GetMapping("/receiver/{uid}")  // 确保路径正确
    public Result getMessagesByReceiver(@PathVariable("uid") Integer uid) {
        List<Message> messages = messageService.getMessagesByReceiver(uid);
        return Result.success(messages);
    }

    /**
     * 根据用户ID查询发送的消息
     */
    @GetMapping("/sender/{uid}")
    public Result getMessagesBySender(@PathVariable("uid") Integer uid) {
        List<Message> messages = messageService.getMessagesBySender(uid);
        return Result.success(messages);
    }

    /**
     * 查询用户相关的所有消息（包括发送和接收的）
     */
    @GetMapping("/user/{uid}")
    public Result getUserMessages(@PathVariable("uid") Integer uid) {
        List<Message> messages = messageService.getUserMessages(uid);
        return Result.success(messages);
    }
}